package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TBackAdminUser;
import model.VBackAdminUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;
import util.toolkit.TimeUtil;

/**
 * 后台用户信息管理
 * @author djf
 * @since 2018/12/11
 */

@Controller
@RequestMapping(value="/sysadminusermanager")
public class SysAdminUserManagementController {

	/**
	 * 后台用户信息添加
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 后台用户信息添加
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个后台用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.addAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "后台用户管理/后台用户添加")
	@RequestMapping(value="/addadminuser")
	public String addAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TimeUtil tUtil=new TimeUtil();
		TBackAdminUser adminuser=new TBackAdminUser();
		
		try {
			String userid=req.getParameter("userid");
			String mobile=req.getParameter("mobile");
			String pwd=req.getParameter("pwd");
			String roleId=req.getParameter("roleId");
			String realname=req.getParameter("realname");
			
			if(userid!=null && !userid.equals("") && mobile!=null && !mobile.equals("")
				&& pwd!=null && !pwd.equals("") && roleId!=null && !roleId.equals("")
				&& realname!=null && !realname.equals("")){
				adminuser.setUserid(userid);
				adminuser.setMobile(mobile);
				adminuser.setPwd(pwd);
				adminuser.setRoleId(Integer.parseInt(roleId));
				adminuser.setUserstatus(Constant.ADMINUSERTRUE);
				adminuser.setRealname(realname);
				adminuser.setCreatetime(tUtil.toTimestamp(new Date()).toString());
				
				boolean row=DAOFactory.getBackAdminUserDAO().addAdminUser(adminuser);
				if(row){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "后台用户添加成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "后台用户添加失败！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "后台用户添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "后台用户添加失败！");
		}
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 根据查询条件得到后台用户信息(带分页)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 根据查询条件得到后台用户信息(带分页)
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "获取后台用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.getAdminUserByStrwhere(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "后台用户管理/后台用户查看")
	@RequestMapping(value="/getadminuserbystrwhere")
	public String getAdminUserByStrwhere(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp=new Expression();
		
		try {
			String username=req.getParameter("username");
			String roldid=req.getParameter("roldid");
			String currentPage=req.getParameter("page");
			String pageSize=req.getParameter("limit");
			
			if(username!=null && !username.equals("")){
				exp.andLeftBraLike("userid", username, String.class);
				exp.orRightBraLike("realname", username, String.class);
			}
			if(roldid!=null && !roldid.equals("")){
				exp.andEqu("roleId", Integer.parseInt(roldid), Integer.class);
			}
			exp.andEqu("userstatus", Constant.ADMINUSERTRUE, Integer.class);
			exp.orderByDesc("createtime");
			List<VBackAdminUser> list=DAOFactory.getBackAdminUserDAO().
					getAdminUserByWhere(exp.toString(), Integer.parseInt(currentPage), Integer.parseInt(pageSize));
			List<VBackAdminUser> listsize=DAOFactory.getBackAdminUserDAO().getAdminUserByWhere(exp.toString());
			if(list!=null && list.size()>0 && listsize.size()>0){
				result.put("code", 0);
				result.put("msg", "查询成功！");
				result.put("count", listsize.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			}else{
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("msg", "无查询结果！");
		}
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 修改后台用户信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 修改后台用户信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个后台用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.updateAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "后台用户管理/后台用户查看")
	@RequestMapping(value="/updateadminuser")
	public String updateAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String userid=req.getParameter("userid");
			String mobile=req.getParameter("mobile");
			String realname=req.getParameter("realname");
			
			if(userid!=null && !userid.equals("") && mobile!=null && !mobile.equals("")
				&& realname!=null && !realname.equals("")){
				TBackAdminUser adminuser=DAOFactory.getBackAdminUserDAO().getTBackAdminUser(userid);
				adminuser.setMobile(mobile);
				adminuser.setRealname(realname);
				
				boolean row=DAOFactory.getBackAdminUserDAO().updateAdminUser(adminuser);
				if(row){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "后台用户修改成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "后台用户修改失败！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "后台用户修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "后台用户修改失败！");
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 删除一个后台用户信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 删除一个后台用户信息
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个后台用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.deleteAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "后台用户管理/后台用户查看")
	@RequestMapping(value="deleteadminuser")
	public String deleteAdminUser(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String userid=req.getParameter("userid");
			
			if(userid!=null && !userid.equals("")){
				TBackAdminUser adminuser=DAOFactory.getBackAdminUserDAO().getTBackAdminUser(userid);
				adminuser.setUserstatus(Constant.ADMINUSERFALSE);
				
				boolean row=DAOFactory.getBackAdminUserDAO().updateAdminUser(adminuser);
				if(row){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "后台用户删除成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "后台用户删除失败！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "后台用户删除失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "后台用户删除失败！");
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 后台用户登录控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 后台用户登录控制类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "后台用户登录", 
			operationClassPath = "controller.SysAdminUserManagementController.adminUserLogin(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "后台登录")
	@RequestMapping(value="/adminuserlogin")
	public String adminUserLogin(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session=req.getSession();
		
		try {
			String userid=req.getParameter("userid");
			String pwd=req.getParameter("pwd");
			
			if(userid!=null && !userid.equals("") && pwd!=null && !pwd.equals("")){
				VBackAdminUser adminuser=DAOFactory.getBackAdminUserDAO().loginBack(userid, pwd);
				if(adminuser!=null){
					session.setAttribute("backUser", adminuser);
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "登录成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "账号不存在或用户名密码错误！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "请输入用户名或密码！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，登录失败！");
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}
	
	
	/**
	 * 退出网站后台系统
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 退出网站后台系统
	@RequestMapping(value="/logoutsystem")
	public String logoutSystem(Model model, HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session=req.getSession();
		
		try {
			session.removeAttribute("backUser");		
			result.put("code", ResponseJSON.FLAG_SUCC);
			result.put("msg", "退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现错误，退出失败！");
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 后台登录用户密码修改()
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 后台登录用户密码修改()
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "后台用户密码修改", 
			operationClassPath = "controller.SysAdminUserManagementController.changePwd(Model model, HttpServletRequest req, HttpServletResponse resp)", 
			operationMenu = "后台密码修改")
	@RequestMapping(value="/changepwd")
	public String changePwd(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");		
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
			
		try {		
			VBackAdminUser backuser=(VBackAdminUser)session.getAttribute("backUser");
			
			String oldpwd = req.getParameter("oldpwd");
			String pwd = req.getParameter("pwd");
			
			if(backuser!=null){
				String userid=backuser.getUserid();
				TBackAdminUser user=(TBackAdminUser)DAOFactory.getBackAdminUserDAO().
						getTBackAdminUser(userid);
				if(user.getPwd()==oldpwd || user.getPwd().equals(oldpwd)){
					user.setPwd(pwd);
					boolean row=DAOFactory.getBackAdminUserDAO().updateAdminUser(user);
					if(row){
						result.put("code",ResponseJSON.FLAG_SUCC);
						result.put("msg", "管理员信息修改成功！");
					}else{
						result.put("code",ResponseJSON.FLAG_FAIL);
						result.put("msg", "管理员信息修改失败，请重试！");
					}
				}else{
					result.put("code",ResponseJSON.FLAG_UNKNOWN_ERORR);
					result.put("msg", "输入旧密码不正确！");
				}				
			}
			else {
				result.put("code",ResponseJSON.FLAG_UNKNOWN_ERORR);
				result.put("msg", "请先登录！！！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code",ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现错误，修改失败，请重试！");
		}
		
		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 得到当前登录的用户信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 得到当前登录的用户信息
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询当前登录用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.getLoginUserDetail(Model model, HttpServletRequest req, HttpServletResponse resp)", 
			operationMenu = "后台个人信息")
	@RequestMapping(value="/getloginuserdetail")
	public String getLoginUserDetail(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");		
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
		try {		
			VBackAdminUser backuser=(VBackAdminUser)session.getAttribute("backUser");
			
			if(backuser!=null){
				String userid=backuser.getUserid();
				VBackAdminUser user=DAOFactory.getBackAdminUserDAO().getVBackAdminUser(userid);
				if(user!=null){
					result.put("code",ResponseJSON.FLAG_SUCC);
					result.put("msg", "管理员信息获取成功！");
					JSONArray jsonArray = JSONArray.fromObject(user);
					result.element("data", jsonArray);
				}else{
					result.put("code",ResponseJSON.FLAG_FAIL);
					result.put("msg", "管理员信息获取失败！");
				}			
			}
			else {
				result.put("code",ResponseJSON.FLAG_UNKNOWN_ERORR);
				result.put("msg", "请先登录！！！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code",ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现错误，修改失败，请重试！");
		}
		
		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 修改当前登录的用户信息（个人信息、修改）
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 修改当前登录的用户信息（个人信息、修改）
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改当前登录用户信息", 
			operationClassPath = "controller.SysAdminUserManagementController.editLoginUserDetail(Model model, HttpServletRequest req, HttpServletResponse resp)", 
			operationMenu = "后台个人信息")
	@RequestMapping(value="/editloginuserdetail")
	public String editLoginUserDetail(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");		
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result = new JSONObject();
		
		try {		
			String userid=req.getParameter("userid");
			String realname=req.getParameter("realname");
					
			TBackAdminUser user=DAOFactory.getBackAdminUserDAO().getTBackAdminUser(userid);
			user.setRealname(realname);
			boolean row=DAOFactory.getBackAdminUserDAO().updateAdminUser(user);
			if(row){
				result.put("code",ResponseJSON.FLAG_SUCC);
				result.put("msg", "管理员信息修改成功！");
			}else{
				result.put("code",ResponseJSON.FLAG_FAIL);
				result.put("msg", "管理员信息修改失败！");
			}			
			
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code",ResponseJSON.FLAG_FAIL);
			result.put("msg", "出现错误，修改失败，请重试！");
		}
		
		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
}
